package com.tich.common.service.impl;

import com.tich.common.domain.vo.CaptchaVO;
import com.tich.common.enumration.ImageType;
import com.tich.common.service.CommonService;
import com.tich.common.utils.AliOssUtil;
import com.tich.constant.ExceptionConstant;
import com.tich.constant.RedisConstant;
import com.tich.exception.FileAnalyseException;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 生成图形验证码
     * @return
     * */
    public CaptchaVO captcha() {
        //生成验证码图片
        SpecCaptcha captcha = new SpecCaptcha();//规定验证码大小
        captcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);//规定验证码组成
        //生成UUID作为验证码的key
        UUID key = UUID.randomUUID();
        //将数据存进redis
        stringRedisTemplate.opsForValue().set(RedisConstant.CAPTCHA_HEAD + key, captcha.text().toLowerCase(), RedisConstant.CAPTCHA_TTL, TimeUnit.SECONDS);
        return CaptchaVO.builder()
                .key(key.toString())
                .img(captcha.toBase64())
                .build();
    }

    /**
     * 上传头像
     * @param files
     * @return
     * */
    public List<String> upload(List<MultipartFile> files, Integer type){
        ImageType imageType = ImageType.getByType(type);
        List<String> urls = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                String originalFilename = file.getOriginalFilename();
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String objectName = imageType.getPath() + UUID.randomUUID() + extension;
                urls.add(aliOssUtil.uploadByte(file.getBytes(), objectName));
            } catch (Exception e) {
                throw new FileAnalyseException(ExceptionConstant.FILE_ANALYSE_FAIL);
            }
        }
        return urls;
    }

}
